<?php


class User {
	
	private $userid;
	private $dbconn;
	
	public function User($dbconn) {
		$this->dbconn = $dbconn;
	}
	
	
	public function save($userdata) {
		if($userdata["id"]) {
			$userdata["email"] = mysql_real_escape_string($userdata["email"], $this->dbconn);
			$userdata["password"] = mysql_real_escape_string($userdata["password"], $this->dbconn);
		} else {
			$userdata["email"] = mysql_real_escape_string($userdata["email"], $this->dbconn);
			
			$nonce = $this->randomString();
			$pass = $this->hash_password(mysql_real_escape_string($userdata["password"]), $nonce);
			
			
			$userdata["password"] = $pass;
			$userdata["nonce"] = $nonce;
			
			// Check if the username is taken
			$query = "SELECT COUNT(id) AS count FROM users where email='".$userdata["email"]."';";
			$res = mysql_query($query, $this->dbconn);
			$row = mysql_fetch_assoc($res);
			if($row["count"] > 0) {
				return false;
			} 
			
			// Save
			$query = "INSERT INTO users (email, password, nonce) VALUES ('".$userdata["email"]."','".$userdata["password"]."','".$nonce."');";
			$res = mysql_query($query, $this->dbconn);
			if(mysql_errno($this->dbconn) > 0) {
				return false;
			} 
			
			return true;
		}
	}
	
	
	private function randomString() {
		$string = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_-!";
		$shuffle = str_shuffle($string);
		$cutoff_start = mt_rand(1, 10);
		$cutoff_end = mt_rand($cutoff_start+5, $cutoff_start+5+10);
		return substr($shuffle, $cutoff_start, $cutoff_end);
	}
	
	private function hash_password($password, $nonce) {
		return hash_hmac('sha512', $password . $nonce, $this->getSiteKey());
	}
	
	private function getSiteKey() {
		return "Th1s secret key should not be stored like this, in pl4in site. Rather it should be more secret!?";
	}
	
	
}